package com.service.impl;

import com.service.EmailService;
import com.utils.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
import java.time.LocalDateTime; // 用于处理验证码有效期

@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private EmailUtil emailUtil;
    private final JavaMailSender mailSender;

    private final Map<String, VerificationCodeInfo> verificationCodes = new ConcurrentHashMap<>();

    public static final long VERIFICATION_CODE_VALID_MINUTES = 5;

    public EmailServiceImpl(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    private static class VerificationCodeInfo {
        String code;
        LocalDateTime sentTime;

        public VerificationCodeInfo(String code, LocalDateTime sentTime) {
            this.code = code;
            this.sentTime = sentTime;
        }

        public boolean isValid() {
            // 检查当前时间是否在发送时间之后，且在有效期内
            return LocalDateTime.now().isBefore(sentTime.plusMinutes(VERIFICATION_CODE_VALID_MINUTES));
        }
    }

    private String generateVerificationCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        return String.valueOf(code);
    }

    @Override
    public boolean sendVerificationCode(String toEmail) {
        try {
            String code = generateVerificationCode();
            verificationCodes.put(toEmail, new VerificationCodeInfo(code, LocalDateTime.now()));

            emailUtil.sendVerificationCodeAsync(toEmail, code);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }



    @Override
    public boolean verifyCode(String email, String code) {
        VerificationCodeInfo storedInfo = verificationCodes.get(email);

        if (storedInfo == null) {
            // 邮箱不存在或验证码已过期/未发送
            return false;
        }

        if (!storedInfo.isValid()) {
            verificationCodes.remove(email); // 移除过期验证码
            return false;
        }

        // 验证输入的验证码是否正确
        // 这里不立即移除验证码，以便在注册成功后再清除
        return storedInfo.code.equals(code);
    }

    /**
     * 清除某个邮箱的验证码 (在注册成功后调用)
     * @param email 邮箱地址
     */
    public void clearVerificationCode(String email) {
        verificationCodes.remove(email);
    }

}
